import logging

from fastapi import FastAPI
from fastapi.logger import logger
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from config import CONFIG
from routers import router
from ext import redis
from config.data import opotions
from models import Opotions

app = FastAPI(title=CONFIG.APP_NAME, docs_url=None, redoc_url=None)
app.include_router(router)

# app.add_middleware(SessionMiddleware, secret_key='YOUR KEY', max_age=3600 * 6)
# origins = ['*']
# app.add_middleware(CORSMiddleware,
#                    allow_origins=origins,
#                    allow_credentials=True,
#                    allow_methods=["*"],
#                    allow_headers=["*"])


gunicorn_logger = logging.getLogger('gunicorn.error')
logger.handlers = gunicorn_logger.handlers
logger.setLevel(gunicorn_logger.level)

register_tortoise(
    app,
    db_url=CONFIG.DB_URL,
    modules={"models": ["models"]},
    generate_schemas=True,
    add_exception_handlers=False
)


async def init_db():
    exist = await Opotions.exists()
    if not exist:
        for k, v in opotions.items():
            father = await Opotions.create(name=k)
            for i in v:
                await Opotions.create(name=i, fid=father.pk)


async def init_cache():
    name = 'opotions'
    exist = await redis.client.exists(name)
    if not exist:
        fathers = await Opotions.filter(fid=None).all()
        for f in fathers:
            sons = await Opotions.filter(fid=f.pk).all()
            value = [{'id': son.pk, 'name': son.name} for son in sons]
            await redis.client.hset(name, f.pk, str(value))


@app.on_event("startup")
async def event_startup():
    await redis.connect(url=CONFIG.REDIS_URL)
    await init_db()
    await init_cache()
    logger.info('START')


@app.on_event("shutdown")
async def event_shutdown():
    await redis.disconnect()
    logger.info('STOP')
